# -*- coding: utf-8 -*-

import string, re
import pepe.glib as g
import dtective_tests_numeric as tn
import pepe.p_datetime.basic as dt
import pepe.p_datetime.holiday as dh
import pepe.p_datetime.date_format as df

class Dtective:
    """ """
    def __init__(self):
        """ """
        self.varType = ''
        self.varName = ''
        self.debug = False
        self.varIndex = 1
        self.idIndex = 0
        self.run_missingValue = 1
        self.n_sl_roundedAmount       = [8, 7, 6, 5, 4, 3]
        self.n_sl_sequenceAmount      = [      6, 5, 4, 3]
        self.n_sl_repeatNumbersAmount = [      6, 5, 4, 3, 22, 33, 44]
        self.d_country_isholiday      = 'cz'
        self.fyPeriodIndex = ''

    def testsNumeric(self):
        """ """
        self.varName = string.upper(self.varName)

        if tn.roundedAmount(self.rowVal, strLen=self.n_sl_roundedAmount):
            self.o.write("%s\tamount.rounded_value.%s\t%s\t%s\n" % \
            (self.rowId, self.varName, self.rowVal, self.rowFull))

        if tn.sequenceAmount(self.rowVal, strLen=self.n_sl_sequenceAmount):
            self.o.write("%s\tamount.sequence_value.%s\t%s\t%s\n" % \
            (self.rowId, self.varName, self.rowVal, self.rowFull))

        if tn.repeatNumbersAmount(self.rowVal, strLen=self.n_sl_repeatNumbersAmount):
            self.o.write("%s\tamount.repeated_value.%s\t%s\t%s\n" % \
            (self.rowId, self.varName, self.rowVal, self.rowFull))
            
    def testsDate(self):
        """ """
        dateVal = df.date2iso(self.rowVal)
        self.varName = string.upper(self.varName)
        
        try:
            if dt.isWeekend(dateVal):
                self.o.write("%s\tdate.weekend.%s\t%s\t%s\n" % \
                (self.rowId, self.varName, dateVal, self.rowFull))
        except ValueError:
            print self.rowVal,' - ',dateVal,' ',self.rowFull
            raise "err"

        if dh.isHoliday(dateVal, self.d_country_isholiday):
            self.o.write("%s\tdate.holiday.%s.%s\t%s\t%s\n" % \
            (self.rowId, self.d_country_isholiday, self.varName, dateVal, self.rowFull))

    def testsMissingValue(self):
        if tn.missingValue(self.rowVal):
            self.o.write("%s\tmissing_value.%s\t%s\t%s\n" % \
            (self.rowId, self.varName, self.rowVal, self.rowFull))


    def runTests(self):
        """ """
        i = open(self.inputFile, 'r')
        self.o = open(self.outputFile, 'a')

        lino = 0
        for line in i.readlines():
            if self.debug == True: print line,
            lino += 1

            # write header line(s) from input file(s)
            if lino == 1:
                h = open('#headers.out', 'a')
                h.write(self.inputFile+'\t'+line)
                h.close()

            self.rowFull = re.sub('\n', '', line)
            cols = string.split(line, '\t')

            # 2010-09-20_0223 vp (index of rowVal should start from 1 because of csvh output)
            self.rowVal = cols[self.varIndex - 1]

            #self.rowVal = g.string2number(self.rowVal)
            
            # 2010-09-22_1035 vp (index rowId should start from 1 because of csvh output)
            self.rowId = cols[self.idIndex - 1]

            if self.run_missingValue ==  1 : self.testsMissingValue()
            if self.debug == True: 
                print ">", self.rowVal, "<"
            if self.varType == 'N':
                self.rowVal = g.string2number(self.rowVal)
                self.testsNumeric()
            if self.varType == 'D': self.testsDate()

        i.close()
        self.o.close()

    def listAlldata(self):
        """ """
        i = open(self.inputFile, 'r')
        self.o = open(self.outputFile, 'a')
        lino = 0
        for line in i.readlines():
            if self.debug == True: print line,
            lino += 1
            if lino > 1:
                self.rowFull = re.sub('\n', '', line)
                cols = string.split(line, '\t')
                '''
                fy = ''
                # ??? what is this ???
                if cols[1] == 'zzc':
                    #print cols[11]
                    fy = (df.date2iso(cols[11]))[:4]
                if cols[1] == 'zzd':
                    #print cols[8]
                    fy = (df.date2iso(cols[8]))[:4]
                '''
                # 2010-09-20_0223 vp (index should start from 1 because of csvh output) 
                self.rowVal = cols[self.varIndex - 1]
                try:
                    self.rowVal = g.string2number(self.rowVal)
                except:
                   # print line
                    raise "fdsfds"
                #self.rowVal = g.string2number(self.rowVal)
                self.rowId = cols[self.idIndex].strip()
                
                self.fyPeriod = cols[self.fyPeriodIndex - 1]
                
                #self.o.write("%s\t%s.all_items.%s.%s\t%s\t%s\n" % \
                #(self.rowId, fy, self.inputFile, self.varName, self.rowVal, self.rowFull))
                self.o.write("%s\t%s.all_items.%s.%s\t%s\t%s\n" % \
                (self.rowId, self.fyPeriod, self.inputFile, self.varName, self.rowVal, self.rowFull))
                #self.o.write("%s\tall_items.%s.%s\t%s\t%s\n" % \
                #(self.rowId, self.inputFile, self.varName, self.rowVal, self.rowFull))


        i.close()
        self.o.close()

if __name__ == '__main__':
    if 1:
        print """
        Dtective.py should be used as module.

        Example:

        import pepe.p_dm.dtective as d

        i = d.Dtective()
        
        ## test numeric columns ######################################
        i.outputFile = '#results.txt'; i.varType = 'N'; i.idIndex = 0
        
        i.n_sl_roundedAmount = [8, 7, 6, 5, 4, 3]
        i.n_sl_sequenceAmount = [6, 5, 4, 3] 
        #i.n_sl_sequenceAmount = [6, 5, 4] # all 153 hits only
        i.n_sl_repeatNumbersAmount = [6, 5, 4, 3, 22, 33, 44]
        #i.n_sl_repeatNumbersAmount = [6, 5, 4, 22, 33, 44] # all 153 hits only
        
        i.inputFile = 'aaa-sl-fy2009.csv'
        i.varIndex =  8; i.varName = "DocTotal_"    ; i.runTests()
        i.varIndex =  9; i.varName = "Netto_"       ; i.runTests()
        
        i.inputFile = 'aab-sl-fy2010.csv'
        i.varIndex =  8; i.varName = "DocTotal_"    ; i.runTests()
        i.varIndex =  9; i.varName = "Netto_"       ; i.runTests()
        
        ## test date columns ######################################
        i.outputFile = '#results.txt'; i.varType = 'D'; i.idIndex = 0
        
        i.inputFile = 'aaa-sl-fy2009.csv'
        i.varIndex =  6; i.varName = "DocDate_"     ; i.runTests()
        i.varIndex =  7; i.varName = "DocDueDate_"  ; i.runTests()
        
        i.inputFile = 'aab-sl-fy2010.csv'
        i.varIndex =  6; i.varName = "DocDate_"     ; i.runTests()
        i.varIndex =  7; i.varName = "DocDueDate_"  ; i.runTests()
        """


